package cn.com.api.controller;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.com.api.entity.*;
import cn.com.api.entity.base.U_favoriteBase;
import cn.com.api.service.*;
import cn.com.api.service.base.U_article_replyServiceBase;

import cn.com.util.*;

/**
 * 文章模块api控制器
 * 
 * @return
 */

@Controller
@RequestMapping(Utils.SYS_API + "article/")
public class ApiU_articleController {

	private static Logger logger = Logger.getLogger(ApiU_articleController.class);

	@Autowired
	private U_cateService U_cateService;
	@Autowired
	private U_articleService u_articleService;
	@Autowired
	private ApiU_article_replyService apiU_article_replyService;
	@Autowired
	private U_labelService u_labelService;
	@Autowired
	private ApiT_user_adminService apiT_user_adminService;
	@Autowired
	private U_article_cateService u_article_cateService;
	@Autowired
	private StartOnLoadService startOnLoadService;
	@Autowired
	private ApiU_favoriteService apiU_favoriteService;
	@Autowired
	private ApiU_followService apiU_followService;
	@Autowired
	private CheckService checkService;

	/**
	 * 根据分类获取文章列表(推荐除外)
	 * 
	 * @param cateid
	 *            分类id集合
	 * @param title
	 *            标题
	 * @param user_id
	 *            用户id
	 * @param token
	 * 
	 * @param currentPage
	 *            页数
	 * @param showCount
	 *            每页显示数
	 * @return
	 */
	@RequestMapping(value = "getarticlelist")
	public void getarticlelist(HttpServletRequest request, HttpServletResponse response, String cate_id,
			String cate_name, String title, String user_id, String token, PageInfo page) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map param = new HashMap();
			param.put("cate_id", cate_id);
			param.put("cate_name", cate_name);
			if (title != null && !"".equals(title)) {
				param.put("title", title);
			}
			List<U_article> u_articles = u_articleService.findU_articlesByMap(param, page);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作完成");
			map.put(Utils.DATAS, u_articles);
			map.put(Utils.Page, page);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 获取自媒体所发的头条
	 * 
	 * @param user_id
	 * 
	 * @param token
	 * 
	 * @param to_uid
	 *            要查看自媒体所属的user_id
	 * 
	 * @param currentPage
	 *            页数
	 * @param showCount
	 *            每页显示数
	 * @return
	 */
	@RequestMapping(value = "getArticleListByUserID")
	public void getArticleListByUserID(HttpServletRequest request, HttpServletResponse response, String user_id,
			String token, String to_uid, PageInfo page) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (checkService.checkToken(user_id, token, map)) {
				Map<String, String> params = new HashMap<String, String>();
				params.put("to_uid", to_uid);
				if (!user_id.equals(to_uid)) {
					params.put("status", "1");
				}
				List<U_article> u_articles = u_articleService.findU_articlesByUserID(params, page);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "操作完成");
				map.put(Utils.DATAS, u_articles);
				map.put(Utils.Page, page);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 查找文章by Title
	 * 
	 * @param keyword
	 *            关键词
	 * @param user_id
	 *            用户id
	 * @param token
	 * 
	 * @param currentPage
	 *            页数
	 * @param showCount
	 *            每页显示数
	 * @return
	 */
	@RequestMapping(value = "searcharticlelist")
	public void searcharticlelist(HttpServletRequest request, HttpServletResponse response, String keyword,
			PageInfo page) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map param = new HashMap();

			List<U_article> u_articles = u_articleService.seachU_articles(keyword, page);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作完成");
			map.put(Utils.DATAS, u_articles);
			map.put(Utils.Page, page);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 根据文章ID获取文章内容
	 * 
	 * @param article_id
	 *            文章id
	 * @param article_type
	 *            文章类型
	 * @param user_id
	 *            用户id
	 * @param token
	 * 
	 * @return
	 */
	@RequestMapping(value = "getarticle")
	public void getarticle(HttpServletRequest request, HttpServletResponse response, String article_id, String user_id,
			String token) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map<String, String> params = new HashMap<String, String>();
			params.put("article_id", article_id);
			// params.put("article_type", article_type);

			if (!Util.isNull(user_id)) {
				params.put("user_id", user_id);
				// params.put("token", token);
			}
			if (checkService.checkParams(params, map)) {
				// article_type:类型0：列表1个图片， 1：列表3个图片， 2：图说， 3：视频
				U_article article = u_articleService.findU_articleInfoByMap(params);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "操作完成");
				map.put(Utils.DATAS, article);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 查询文章分类信息
	 * 
	 * @param parentid
	 *            文章分类父id 1：获取头条下所有分类
	 * 
	 * @param user_id
	 *            用户id
	 * @param token
	 * 
	 * @return
	 */
	@RequestMapping(value = "getarticlecates")
	public void getarticlecates(HttpServletRequest request, HttpServletResponse response, String parentid,
			String user_id, String token, String city) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		// 根据传入user_id判断分类是否被用户收藏
		try {
			List<U_cate> list = new ArrayList<U_cate>();
			// if (Util.isNull(user_id)) {
			// list = U_cateService.getArticleCates(Integer.valueOf(parentid),
			// null);
			// } else {
			// list = U_cateService.getArticleCates(Integer.valueOf(parentid),
			// Integer.valueOf(user_id));
			//
			if (Util.isNull(user_id)) {
				list = U_cateService.getArticleCates(Integer.valueOf(parentid), null, city);
			} else {
				list = U_cateService.getArticleCates(Integer.valueOf(parentid), Integer.valueOf(user_id), city);
			}

			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作完成");
			map.put(Utils.DATAS, list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 更新用户关注频道
	 * 
	 * @param cate_ids
	 *            文章分类id,多个用:分隔
	 * 
	 * @param user_id
	 *            用户id
	 * @param token
	 * 
	 * @return
	 */
	@RequestMapping(value = "updateMyCates")
	public void updateMyCates(HttpServletRequest request, HttpServletResponse response, String cate_ids, String user_id,
			String token) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			Map<String, String> params = new HashMap<String, String>();
			params.put("cate_ids", cate_ids);

			if (checkService.checkToken(user_id, token, map) && checkService.checkParams(params, map)) {
				this.U_cateService.updateUserArticleCates(cate_ids, user_id);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "操作完成");
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 获取用户收藏5头条，关注3自媒体(文章)；评论的数量
	 * 
	 * @param user_id
	 *            用户id
	 * @param token
	 * 
	 * @return
	 */
	@RequestMapping(value = "myArticleInfo")
	public void myArticleInfo(HttpServletRequest request, HttpServletResponse response, String user_id, String token)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map param = new HashMap();
			param.put("user_id", user_id);
			param.put("type", 5);
			Integer favoriteCount = apiU_favoriteService.getFavoriteCount(param);
			param.put("type", 3);
			Integer followCount = apiU_followService.getFollowCount(param);
			Integer commentCount = u_articleService.getCommentCountByMap(param);

			param.clear();
			param.put("favoriteCount", favoriteCount);// 收藏文章的数量
			param.put("followCount", followCount); // 关注文章的数量
			param.put("commentCount", commentCount); // 评论的数量
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作完成");
			map.put(Utils.DATAS, param);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 推荐频道文章
	 * 
	 * @param user_id
	 *            用户id
	 * @param token
	 * 
	 * @return
	 */
	@RequestMapping(value = "getRecommendArticles")
	public void getRecommendArticles(HttpServletRequest request, HttpServletResponse response, String user_id,
			String token, PageInfo page) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			List<U_article> artList = new ArrayList<U_article>();
			if (Util.isNull(user_id))// 未登录
			{
				artList = this.u_articleService.getRecommendArticles(null, page);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "操作完成");
				map.put(Utils.DATAS, artList);
			} else {
				if (checkService.checkToken(user_id, token, map)) {
					artList = this.u_articleService.getRecommendArticles(user_id, page);
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "success");
					map.put(Utils.DATAS, artList);
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 评论文章（评论文章和at评论）
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("replyArticleByID")
	public void replyArticleByID(HttpServletRequest request, HttpServletResponse response, String user_id, String token,
			String article_id, String comment_content, String user_name, String to_id, String to_uname)
			throws Exception {

		// String user_id = request.getParameter("user_id");//评论人ID
		// String token = request.getParameter("token");
		// String article_id = request.getParameter("dynamic_id");//文章ID
		// String comment_content = request.getParameter("reply_content");
		// String user_name = request.getParameter("user_name");//评论人姓名
		// String to_id = request.getParameter("to_uid");//被at人的ID, 为-1时，表示评论文章
		// String to_uname = request.getParameter("to_uname");//被at人的姓名

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (checkService.checkToken(user_id, token, map)) {
				// 保存评论内容
				ApiU_article_reply article_reply = new ApiU_article_reply();
				article_reply.setArticle_id(article_id);
				article_reply.setUser_id(user_id);
				article_reply.setUser_name(user_name);
				article_reply.setReply_content(comment_content);
				article_reply.setTo_uid(to_id);
				article_reply.setTo_uname(to_uname);
				article_reply.setAdd_time(Util.CurrentTime());
				article_reply.setIs_delete(0);
				apiU_article_replyService.U_article_replyInsertion(article_reply);

				// return
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "评论成功！");
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 删除评论内容（仅自己可以删除自己的）
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("DelArticle_ReplyByID")
	public void DelArticle_ReplyByID(HttpServletRequest request, HttpServletResponse response, String user_id,
			String token, String id) throws Exception {

		// String user_id = request.getParameter("user_id");
		// String token = request.getParameter("token");
		// String id = request.getParameter("id");
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (checkService.checkToken(user_id, token, map)) {
				ApiU_article_reply article_reply = apiU_article_replyService
						.findU_article_replyById(Integer.valueOf(id));
				article_reply.setIs_delete(1);
				apiU_article_replyService.updateU_article_reply(article_reply);
				// return
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "删除成功！");
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		JsonUtil.printJson(response, JsonUtil.object2json(map));

	}

	/**
	 * 我的评论列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("getMyArticleCommentList")
	public void getMyArticleCommentList(HttpServletRequest request, HttpServletResponse response, String user_id,
			String token, PageInfo page) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (checkService.checkToken(user_id, token, map)) {
				Map<String, String> params = new HashMap<String, String>();
				params.put("user_id", user_id);

				List<ApiU_article_reply> reply_list = apiU_article_replyService.findU_article_replysByUserID(params,
						page);

				// return
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "操作成功！");
				map.put(Utils.DATAS, reply_list);
				map.put(Utils.Page, page);
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		JsonUtil.printJson(response, JsonUtil.object2json(map));

	}

	/**
	 * 文章评论列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("getArticleCommentList")
	public void getArticleCommentList(HttpServletRequest request, HttpServletResponse response, String user_id,
			String token, String article_id, PageInfo page) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// if (checkService.checkToken(user_id, token, map)) {
			Map<String, String> params = new HashMap<String, String>();
			params.put("article_id", article_id);

			List<ApiU_article_reply> reply_list = apiU_article_replyService.findU_article_replysByUserID(params, page);

			// return
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作成功！");
			map.put(Utils.DATAS, reply_list);
			map.put(Utils.Page, page);
			// }
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		JsonUtil.printJson(response, JsonUtil.objectToJsonStr(map));

	}

	/**
	 * 我的评论列表(头条)
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("getAllCommentList")
	public void getAllCommentList(HttpServletRequest request, HttpServletResponse response, String user_id,
			String token, PageInfo page) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (checkService.checkToken(user_id, token, map)) {
				Map<String, String> params = new HashMap<String, String>();
				params.put("user_id", user_id);

				List<ApiU_article_reply> reply_list = apiU_article_replyService.findU_article_replysByUserID(params,
						page);

				// return
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "操作成功！");
				map.put(Utils.DATAS, reply_list);
				map.put(Utils.Page, page);
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 首页显示的滚动头条
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("getRollArticleList")
	public void getRollArticleList(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			List<U_article> article_list = this.u_articleService.getHomePageArticleList();
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作成功！");
			map.put(Utils.DATAS, article_list);

		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}
}
